<?php
namespace App\Repositories;

use App\Models\Cimo\Exam;

class ExamRepository
{
    use BaseRepository;
    
    private $model;
    
    public function __construct(Exam $exam)
    {
        $this->model = $exam;
    }
    
    public function getLists($companyId = 0,$pageSize = 20)
    {
        if($companyId) {
            return $this->model->where('company_id', $companyId)->orderBy('created_at', 'desc')->paginate($pageSize);
        } else {
            return $this->model->orderBy('created_at','desc')->paginate($pageSize);
        }
    }
    
    public function getByName($companyId, $name)
    {
        return $this->model->where('company_id',$companyId)->where('name',$name)->first();
    }
    
    public function getExam($id)
    {
        return $this->getById($id);
    }
    
    public function getRandExam()
    {
        return $this->model->where('company_id',0)->where('question_count','>',0)->where('score_count','>',0)->orderByRaw('RAND()')->take(1)->value('id');
    }
    
    /**
     * 获取试卷信息，包括已删除的试卷
     * @param int $id
     * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|NULL
     */
    public function getTrashedExam($id,$with='')
    {
        if($with)
            return $this->model->withTrashed()->has('questions')->with($with)->find($id);
        else 
            return $this->model->withTrashed()->has('questions')->find($id);
    }
    
    /**
     * store.
     *
     * @param array $input
     */
    public function store($input)
    {
        return $this->savePost($this->model, $input);
    }
    
    /**
     * 更新
     * @param int $id
     * @param $input
     * @return \App\Models\AccountEvents
     */
    public function update($id, $input)
    {
        $model = $this->model->find($id);
    
        return $this->savePost($model, $input);
    }
    
    /**
     * save.
     *
     * @param Request $input 输入
     */
    public function savePost($events, $input)
    {
        $events->fill($input);
        $events->save();
    
        return $events;
    }
}

